var express = require('express');
var router = express.Router();
var image = require("imageinfo");

var fs = require('fs');
/* GET home page. */
// /android
router.get('/', function (req, res, next) {

  var androidUrl = req.protocol + '://' + req.get('host') + "/";
  //   var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;

  function readFileListAll(path, filesList) {
    var files = fs.readdirSync(path);
    files.forEach(function (itm, index) {
      var stat = fs.statSync(path + itm);
      if (stat.isDirectory()) {
        //递归读取文件
        readFileListAll(path + itm + "/", filesList)
      } else {
        var obj = {}; //定义一个对象存放文件的路径和名字
        obj.path = path; //路径
        obj.filename = itm //名字
        obj.isfile = true;
        filesList.push(obj);
      }
    });
  }

  function readFileListTree(path, filesList) {
    try{
      console.log(path);
      var files = fs.readdirSync(path);
    }catch (e) {
      console.error("不存在的文件夹 " , path);
      res.send({
        code: 100,
        msg: '不存在的文件夹',
        data: {
          dir: req.query.dir,
          list: []
        }
      });
    }
    files.forEach(function (itm, index) {
      var stat = fs.statSync(path + itm);
      if (stat.isDirectory()) {
        var obj = {}; //定义一个对象存放文件的路径和名字
        obj.path = (path + itm).replace('../www/', ''); //路径
        obj.filename = itm //名字
        obj.isfile = false;
        obj.child = [];
        //递归读取文件
        readFileListTree(path + itm + "/", obj.child)
        filesList.push(obj);
      } else {
        var obj = {}; //定义一个对象存放文件的路径和名字
        obj.path = (androidUrl + path + itm).replace('../www/', ''); //路径
        obj.filename = itm //名字
        obj.isfile = true;
        filesList.push(obj);
      }
    });
  }
  var getFiles = {
    getFileList: function (path) {
      var filesList = [];
      readFileListAll(path, filesList);
      return filesList;
    },
    getFilesTree: function (path) {
      var filesListTree = [];
      readFileListTree(path, filesListTree);
      return filesListTree;
      // res.send(filesListTree);
    },
    getImageFiles: function (path) {
      var imageList = [];
      this.getFileList(path).forEach((item) => {
        var ms = image(fs.readFileSync(item.path + item.filename));

        ms.mimeType && (imageList.push(item.path + item.filename))
      });
      res.send(imageList);
      return imageList;
    }
  };

  // var myfiles = getFiles.getFileList("../public/");
  // var myfiles = getFiles.getImageFiles("../public/");
  var mypath = "../www/android/" + (req.query.dir||'') + ((req.query.dir=='' || req.query.dir==null)?'' : '/');

  var myfiles = getFiles.getFilesTree(mypath);

  res.send({
    code: 100,
    message: '成功',
    data: {
      dir: req.query.dir,
      list: myfiles
    }
  });

});


module.exports = router;